package com.sxt.pro.Ny_data;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**  

* @Description: 农业:爬取页面数据

* @author xinxiaokang  

* @date 2020年10月27日 下午1:40:26

*/
@Controller
@RequestMapping("/pro")
public class Ny_dataController {
	
	@RequestMapping("nowapi")
	@ResponseBody
	public Map<String, Object> nowapi() throws Exception {
		Map<String, Object> map=new HashMap<String, Object>();
		try {
			System.out.println("农行爬取页面数据定时器");
			map.put("贵金属", RMB_GoldData());
			map.put("汇率", RMB_ForeignExchange());
			map.put("利率", RMB_CunKauan());
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("农行爬取页面数据定时器抛出异常");
		}
		return map;
	}
	
	public static void main(String[] args) {
		Ny_dataController ny = new Ny_dataController();
		Map<String, Object> nyData= new HashMap<String, Object>();
		try {
			nyData  = ny.nowapi();
			System.out.println("数据为"+nyData);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * @Description：贵金属   
	 * @return
	 */
	public String RMB_GoldData(){
		//获取异步表格数据接口地址
		String reqUrl = getRequest("http://ewealth.abchina.com/app/data/api/DataService/GoldInfoV2");
		//字符串转为json对象
        JSONObject jb = JSONObject.fromObject(reqUrl);
        String data = jb.getString("Data");
        JSONObject jsdata = JSONObject.fromObject(data);
        //获取贵金属表格数据
        String jsTable = jsdata.getString("Table1");
        //获取json对象中实体数组
        JSONArray ja = JSONArray.fromObject(jsTable );
        //封装数据
        JSONObject jo = new JSONObject();
        Map<String, Object> mapO = new HashMap<String, Object>();
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        
        for (int i = 0; i < ja.size(); i++) {
        	Map<String, Object> map = new LinkedHashMap<String, Object>();
        	//遍历数组，把每个对象转成json对象
        	 JSONObject job= ja.getJSONObject(i);
        	 map.put("ProdName", job.getString("ProdName"));             //品种
        	 map.put("CustomerSell", job.getString("CustomerSell"));     //客户卖出价
        	 map.put("CustomerBuy", job.getString("CustomerBuy"));       //客户买入价
        	 map.put("UpdateTime", job.getString("UpdateTime"));         //提价时间
        	 list.add(map);
		}
        mapO.put("data", list);
		jo.put("body", mapO);
		return jo.toString();
	}
	
	
	
	

	/**
	 * @Description： 汇率
	 * @return
	 */
	public String RMB_ForeignExchange(){
		String reqUrl = getRequest("http://65.push2.eastmoney.com/api/qt/clist/get?pn=1&pz=20&po=1&np=1&ut=bd1d9ddb04089700cf9c27f6f7426281&fltt=2&invt=2&fid=f3&fs=m:162+s:2&fields=f1,f12,f13,f14,f31,f32,f142,f143,f124&_=1603855049037");
		//获取json数据格式
		JSONObject js = JSONObject.fromObject(reqUrl);
		String data = js.getString("data");
		JSONObject jsData = JSONObject.fromObject(data);
		String jsTable = jsData.getString("diff");
		//转换为数组
		JSONArray ja = JSONArray.fromObject(jsTable);
		//封装数据
		JSONObject jo = new JSONObject();
		Map<String, Object> mapO = new  HashMap<String, Object>();
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        for (int i = 0; i < ja.size(); i++) {
        	Map<String, Object> map  = new LinkedHashMap<String, Object>();
        	//转化json对象
        	JSONObject job = ja.getJSONObject(i);
        	map.put("f14", job.getString("f14"));    //名称
        	map.put("f31", job.getString("f31"));    //现汇买入价
        	map.put("f32", job.getString("f32"));    //现汇卖出价
        	list.add(map);
		}
        mapO.put("data", list);
        jo.put("body", mapO);
		return jo.toString();
	}
	
	/**
	 * @Description：利 率  
	 * @return
	 */
	public String RMB_CunKauan(){
		String reqUrl = getHttpRequest("http://www.lilvb.com/cunkuan/24.htm");
		Document doc = Jsoup.parse(reqUrl);
		Element element = doc.select("tbody").get(18);
		//数据封装
		JSONObject jo = new JSONObject();
		Map<String, Object> mapData = new  HashMap<String, Object>();
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        List<Map<String, Object>> listOne = new ArrayList<Map<String, Object>>();
		//获取表格tr数据条数
		Elements elements = element.select("td");
		//获取整存整取数据
		for (int i = 10; i < elements.size(); i++) {
			Map<String, Object> map  = new HashMap<String, Object>();
			Map<String, Object> mapOne  = new LinkedHashMap<String, Object>();
		    if (i== 10 ||i== 12 ||i== 14 ||i== 16 ||i== 18 ||i== 20) {
		    	String text = elements.get(i).text();
		    	String textOne = elements.get(i+1).text();
		    	map.put("CunkuanName", text);
		    	map.put("Cunkuan", textOne);
		    	list.add(map);
		      //零存整取、整存零取、存本取息 数据
			} else if(i== 24||i== 26 ||i== 28) {  
				String textTwo = elements.get(i).text();
				String textThree = elements.get(i+1).text();
				mapOne.put("CunkuanName", textTwo);
				mapOne.put("Cunkuan", textThree);
				listOne.add(mapOne);
			} 
		}
		mapData.put("all", list);
		mapData.put(" zero", listOne);
		jo.put("body", mapData);
		return jo.toString();
	}
	
	
	/**
	 * 发起http请求并获取结果     utf-8格式
	 * 
	 * @param requestUrl
	 *            请求地址
	 */
	public static String getRequest(String requestUrl) {
		String res = "";

		StringBuffer buffer = new StringBuffer();
		try {
			URL url = new URL(requestUrl);
			// 打开连接
			HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();
			if (200 == urlCon.getResponseCode()) {// 连接正常，获取输入流
				InputStream is = urlCon.getInputStream();
				InputStreamReader isr = new InputStreamReader(is, "utf-8");
				BufferedReader br = new BufferedReader(isr);

				String str = null;
				while ((str = br.readLine()) != null) {
					buffer.append(str);
				}
				// 关闭流
				br.close();
				isr.close();
				is.close();
				res = buffer.toString();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return res;
	}

	
	
	/**
	 * 发起http请求并获取结果        GBK格式  
	 * 
	 * @param requestUrl
	 *            请求地址
	 */
	public static String getHttpRequest(String requestUrl) {
		String res = "";

		StringBuffer buffer = new StringBuffer();
		try {
			URL url = new URL(requestUrl);
			// 打开连接
			HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();
			if (200 == urlCon.getResponseCode()) {// 连接正常，获取输入流
				InputStream is = urlCon.getInputStream();
				InputStreamReader isr = new InputStreamReader(is, "GBK");
				BufferedReader br = new BufferedReader(isr);

				String str = null;
				while ((str = br.readLine()) != null) {
					buffer.append(str);
				}
				// 关闭流
				br.close();
				isr.close();
				is.close();
				res = buffer.toString();
				// 如果是json数据可以这样解析然后返回JsonObject类型的对象
				// JsonParser parse =new JsonParser();
				// JsonObject res2 = (JsonObject)parse.parse(buffer.toString());
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return res;
	}
	
	
	
	
}
